<?php
namespace Home\Model;

use Think\Model\RelationModel;

class UserDataModel extends RelationModel
{
	protected $tableName = 'user_data';
	protected $_link = array(
		'User' => array(
			'mapping_type'  => self::BELONGS_TO,
			'class_name'    => 'User',
			'foreign_key'   => 'user_id',
			'parent_key'    => 'id',
			'mapping_name'  => 'user',
			)
		);
	// protected $fields = array(
	// 		'temperature',
	// 		'humidity',
	// 	);

	protected function _after_select(&$resultSet, $options) {
		parent::_after_select($resultSet, $options);

		if (isset($resultSet[0])) {
			foreach ($resultSet as &$set) {
				$data = json_decode($set['data'], true);

				$set['temperature'] = $data['t'];
				$set['humitity'] = $data['h'];

				$control = json_decode($set['control'], true);
				if ($control['light']) {
					$set['light'] = '开启';
				}
				else {
					$set['light'] = '关闭';
				}
			}

		}
		else {
			$data = json_decode($resultSet['data'], true);

			$set['temperature'] = $data['t'];
			$set['humitity'] = $data['h'];
		}
	}

	protected function _after_find(&$result, $options) {
		parent::_after_find($result, $options);

		if ($result) {
			$data = json_decode($result['data'], true);

			$result['temperature'] = $data['t'];
			$result['humitity'] = $data['h'];
		}
	}
}